import { TotpItem, ITotpInfo, createTotp, createTotpTest } from "../totp-info"

import { IStorage } from "../../bcat/storage/i-storage"
import { Storage } from "../../bcat/storage/storage"


export class TotpStorage  {
  static KeyTotp: string = "TOTP"
  static from(storage: IStorage): TotpStorage {
    return new TotpStorage(storage);
  }
  static fromDefault(): TotpStorage {
    return new TotpStorage(Storage.default());
  }

  storage: IStorage;
  constructor(storage: IStorage) {
    this.storage = storage;
  }

  createTotpInfos(objs: object): ITotpInfo {
    let res = createTotp();
    for(const key in objs){
      if(objs.hasOwnProperty(key)){
        res.setItem(new TotpItem(objs[key]));
      }
    }
    return res
  }

  toObject(infos: ITotpInfo): object {
    let res = {};
    for(const [key, value] of infos){
      if(key !== undefined && value !== undefined){
        res[key] = value.data;
      }
    }
    return res
  }

  load(): ITotpInfo | undefined {
    const o = this.storage.loadObject(TotpStorage.KeyTotp);
    return o !== undefined ? this.createTotpInfos(o) : undefined;
  }

  save(totp: ITotpInfo) : boolean | undefined {
    if(totp !== undefined) {
      const objTotp = this.toObject(totp);
      return this.storage.saveObject(TotpStorage.KeyTotp, objTotp);
    }
    return undefined;
  }

  delete(): object|undefined {
    const r = this.storage.delete(TotpStorage.KeyTotp);
    return (typeof r === 'object') ? r : undefined;
  }

  exists(): boolean {
    return undefined !== this.storage.loadObject(TotpStorage.KeyTotp);
  }
}

export function test() {
  let ts = TotpStorage.from(Storage.default());
  const totp = createTotpTest(); 
  console.log(ts.save(totp) == true);

  const newTotp = ts.load();
  console.log(newTotp)
  console.log(totp);

  ts.delete();
}
